<?php
/**
 *
 * ============================================================================
 * * 版权所有 度拉拉 * *
 * 网站地址: http://www.dlltrip.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author By: 倪宗锋
 * PhpStorm OrderUtil.php
 * Create By 2017/3/10 11:52 $
 */

namespace common\util;

use common\models\FxCommissionInfo;
use common\models\FxUser;
use common\models\OrderContacts;
use common\models\OrderHotelExtra;
use common\models\OrderInfo;
use common\models\OrderMain;
use common\models\PayMain;
use common\models\PayRefush;
use common\models\ProdCategory;
use common\models\ProdMain;
use common\models\ShUser;
use common\service\login\LoginService;
use common\service\pay\PayService;
use common\service\WeChatService;
use yii\base\Exception;
use zzcx\service\home\FreeWalker;
use zzcx\service\home\MenP;

class OrderUtil
{

    /**
     * Des:申请取消订单
     * Name: applyCancelOrder
     * @param $order_id int 订单号
     * @param $is_check int 是否校验，订单可否退款
     * @param $is_send int 是否通知供应取消订单
     * @param $uid int  用户ID
     * @param $u_type int 0系统，1管理员，2分销商，3微信用户
     * @param $is_confrim int 0 是否发送酒店拒单通知。0：默认通知 ，1：酒店拒单通知
     * @return array
     * @author 倪宗锋
     */
    public static function applyCancelOrder($order_id, $is_check = 1, $is_send = 1, $uid = 0, $u_type = 0, $is_confrim = 0)
    {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            //1.判断订单是否可以取消
            $oderMain = new OrderMain();
            $orderInfo = $oderMain->getOrderInfoById($order_id);
            if ($is_check == 1) {//是否校验 是否可以退款
                $isCancel = static::checkOrderCanCancel($orderInfo);
                if ($isCancel['flag'] == false) {
                    $transaction->rollBack();
                    return $isCancel;
                }
            }

            //2.如果订单已支付 则添加退款记录 取消分销商的佣金
            if (in_array($orderInfo['order_status'], [2, 3, 4])) {
                $order_status = 4;//退款
                //2.1添加退款记录  已经存在记录则自动跳出
                $refund = static::addPayRefund($orderInfo);
                if ($refund['flag'] == false) {
                    $transaction->rollBack();
                    return $refund;
                }
                //2.2修改佣金记录 没有佣金记录则自动自动退出
                $setCommission = static::setCommission($order_id);
                if ($setCommission['flag'] == false) {
                    $transaction->rollBack();
                    return $refund;
                }
            } else {
                $order_status = 5;//取消
            }
            //3.修改订单状态 退款 或者 取消
            $canCel = static::cancelOrder($order_id, $order_status);
            if ($canCel['flag'] == false) {
                $transaction->rollBack();
                return $canCel;
            }
            //4.通知供应商订单取消
            if ($is_send == 1) {//是否发送退款请求通知供应商
                //去cs取消订单  不是车票或没有spider_order_id 会自动跳出方法
                $csFlag = static::cancelOrderCsBus($orderInfo);
                if ($csFlag['flag'] == false) {
                    $transaction->rollBack();
                    return $csFlag;
                }
            }
            //5.发送用户通知 目前只有酒店订单发送通知
            static::sendCancelOrderMsg($orderInfo, $is_confrim);
            Util::sendWxMsg(['order_id' => $order_id, 'type' => 5]);//发送微信取消通知
            $transaction->commit();
            if (in_array($orderInfo['order_status'], [2, 3])) {//退款
                Util::addOrderLog($uid, $u_type, $order_id, '申请退款', 5);
            } else {
                Util::addOrderLog($uid, $u_type, $order_id, '自动取消', 4);
            }
            return Util::returnArrSu();
        } catch (Exception $e) {
            $transaction->rollBack();//回滚
            return Util::returnArrEr('订单取消失败！[10000]');
        }
    }

    /**
     * Des:取消订单发送短信通知
     * Name: sendCancelOrderMsg
     * @param $orderInfo
     * @return array
     * @author 倪宗锋
     */
    public static function sendCancelOrderMsg($orderInfo, $is_confirm = 0)
    {
        if (in_array($orderInfo['category_id'], [3]) == false) {
            return Util::returnArrSu();
        }
        $siteConfig = Util::getSiteConfig();
        try {
            $orderMain = new  OrderMain();
            $hotelOrderInfo = $orderMain->getHotelOrderInfo($orderInfo['order_id']);
            $night = count(json_decode($hotelOrderInfo['total_details'], true));
            if ($is_confirm == 0) {
                $msg = "预订失败：订单号{$orderInfo['order_id']}，您预订的{$hotelOrderInfo['start_date']}入住";
                $msg .= "{$hotelOrderInfo['hotel_name']}酒店{$hotelOrderInfo['room_name']}{$hotelOrderInfo['prod_cnt']}间{$night}晚，已支付{$hotelOrderInfo['total_money']}元。";
                $msg .= "稍后会将您支付的全款原路退回您的账户，请注意查收。客服电话：{$siteConfig['kefu_tel']}，遇到任何问题可关注微信公众号“{$siteConfig['web_name']}”，咨询在线客服，服务时间：09:00 - 21:00，祝您旅途愉快！";
            } else {
                $msg = "您预定的{$hotelOrderInfo['start_date']}入住的{$hotelOrderInfo['room_name']}{$hotelOrderInfo['prod_cnt']}间{$night}晚的订单已被酒店确认无房，请您选择其他的房型入住。您所支付的金额将会全额退回您的支付账号。请注意查收。";
            }
            return Util::sendMessage($msg, $hotelOrderInfo['contacts_phone']);
        } catch (Exception $e) {
            return Util::returnArrEr('发送短信通知失败');
        }
    }

    /**
     * Des:判断订单是否可以取消
     * Name: checkOrderCanCancel
     * @param $orderInfo
     * @return array
     * @author 倪宗锋
     */
    private static function checkOrderCanCancel($orderInfo)
    {
        $siteConfig = Util::getSiteConfig();
        if (empty($orderInfo)) {//订单不存在
            return Util::returnArrEr('网络异常，请您稍后再试');
        }
        if ($orderInfo['category_id'] == 1) {//车票只能取消开车前的订单
            $busStart = strtotime($orderInfo['start_date'] . ' ' . $orderInfo['start_time']) - 1800;
            $time = time();
            if ($time > $busStart) {
                return Util::returnArrEr('订单取消失败，已过取消截止时间');
            }
        } elseif (in_array($orderInfo['category_id'], [ 3, 4, 5])) {//门票、酒店、巴士自由行、上门接 订单不允许退款
            return Util::returnArrEr("请您联系客服 {$siteConfig['kefu_tel']} 进行取消和退款。");
        } else {//其他订单
            $start = strtotime($orderInfo['start_date']);
            $date = strtotime(date('Y-m-d'));
            if ($date >= $start) {//只能取消开始之前的订单
                return Util::returnArrEr('订单取消失败，已过取消截止时间');
            }
        }
        if ($orderInfo['category_id'] == 3 && $orderInfo['is_confirm']) {//已确认的 酒店订单不可以退款
            return Util::returnArrEr("请您联系客服 {$siteConfig['kefu_tel']} 进行取消和退款。");
        }
        if (in_array($orderInfo['order_status'], [1, 2]) == false) {//订单状态 1，2取消（支付、未支付） 其他的状态订单不可操作取消
            return Util::returnArrEr("请您联系客服 {$siteConfig['kefu_tel']} 进行取消和退款。");
        }
        return Util::returnArrSu();
    }

    /**
     * Des:取消订单 修改订单状态为5 已取消
     * Name: cancelOrder
     * @param $order_id
     * @param $order_status
     * @return array
     * @author 倪宗锋
     */
    private static function cancelOrder($order_id, $order_status = 5)
    {
        $oderMain = new OrderMain();
        $upFlag = $oderMain->upOrder(['order_status' => $order_status], [$order_id]);
        if ($upFlag == false) {
            return Util::returnArrEr('订单取消失败[10005]');
        } else {
            return Util::returnArrSu();
        }
    }

    /**
     * Des:添加申请退款记录
     * Name: addPayRefund
     * @param $orderInfo
     * @return array
     * @author 倪宗锋
     */
    private static function addPayRefund($orderInfo)
    {
        //校验申请退款数据是否已存在
        $payRefush = new PayRefush();
        $pay = $payRefush->getInfoByOrderId($orderInfo['order_id']);
        if (empty($pay) == false) {//如果已经存在数据 则只需返回成功
            return Util::returnArrSu();
        }
        //判断订单是否支付过
        $payMain = new PayMain();
        $payInfo = $payMain->getPayInfo($orderInfo['order_id']);
        if (empty($payInfo)) {
            return Util::returnArrEr('订单取消失败！[10006]');
        }
        //往退票表提交申请
        $resushArr = [
            'order_id' => $orderInfo['order_id'],
            'pay_order_id' => $payInfo['pay_order_id'],
            'pay_type' => $payInfo['pay_type'],
            'amount_money' => $payInfo['amount_money'],
            'refush_money' => $payInfo['order_money'],
            'fx_uid' => $orderInfo['fx_uid'],
            'sh_uid' => $orderInfo['sh_uid'],
            'status' => 1,
            'create_time' => date('Y-m-d H:i:s'),
            'delete_flag' => 0,
            'category_id' => $orderInfo['category_id'],
            'app_id' => $payInfo['app_id'],
            'open_id' => $payInfo['open_id']
        ];
        $payRefush->attributes = $resushArr;
        $insertFlag = $payRefush->insert();
        if (!$insertFlag) {
            return Util::returnArrEr('add refush fail!');
        }
        return Util::returnArrSu();
    }

    /**
     * Des:修改佣金状态
     * Name: setCommission
     * @param $order_id
     * @return array
     * @author 倪宗锋
     */
    private static function setCommission($order_id)
    {
        $commission = new FxCommissionInfo();
        $commissionInfo = $commission->getInfoByOrderId($order_id);//获取佣金详细
        if (empty($commissionInfo)) {
            return Util::returnArrSu();
        }
        if ($commissionInfo['status'] == '2') {//订单已取消则不可取消
            return Util::returnArrSu('订单取消失败！[10007]');
        }
        if ($commissionInfo['status'] == '3') {//已取消则不在操作
            return Util::returnArrSu();
        }
        $up = $commission->editStatus($order_id, 3);//修改订单状态
        if ($up) {
            return Util::returnArrSu();
        }
        return Util::returnArrEr('订单取消失败！[10008]');
    }

    /**
     * Des:去CS取消订单 - 车
     * Name: CancelOrderCs
     * @param $order_info array
     * @return array
     * @author 倪宗锋
     */
    public static function cancelOrderCsBus($order_info)
    {
        if (empty($order_info['spider_order_id'])) {//没有关联订单ID
            return Util::returnArrSu();
        }
        $send_data = [
            'action' => '',
            'if_link' => 1,
            'order_id' => $order_info['spider_order_id'],
            'sign' => $order_info['spider_order_id'],
            'cancel_reason' => '取消订单'
        ];
        if ($order_info['category_id'] == 1) {//如果是车票
            $send_data['action'] = 'cancel_bus_order';
            $url = '/api/submit-order';
        } elseif ($order_info['category_id'] == 2) {//如果是门票
            $send_data['action'] = 'cancel_ticket_order';
            $url = '/api/submit-order';
        } elseif ($order_info['category_id'] == 3) {//如果酒店
            $url = '/hotel/api/cancel-hotel-order';
            $send_data['HotelID'] = $order_info['hotel_id'];
            $send_data['RoomID'] = $order_info['room_id'];
            $send_data['OrderID'] = 'fx' . $order_info['order_id'];
            $send_data['Reason'] = '订单取消';
            $result = Util::sendCs($send_data, $url, 2, 2);
            return $result;
            #临时模拟成功  ---倪宗锋------++++++++++++++
        } elseif ($order_info['category_id'] == 4) {//如果是巴士自由行
            $send_data['action'] = 'cancel_tourist';
            $url = '/api/submit-order';
        } else {//不是车票和门票则 直接跳出该方法
            return Util::returnArrSu();
        }
        $result = Util::sendCs($send_data, $url, 2, $order_info['system']);
        return $result;
    }

    /**
     * Des:微信支付
     * Name: getWeChatOrderPayParams
     * @return array
     * @author 倪宗锋
     */
    public static function weChatOrderPay()
    {
        $getContent = file_get_contents("php://input");
        $content = Util::xmlToArray($getContent);
        /**支付结果判定*/
        if ($content['result_code'] != 'SUCCESS' || $content['return_code'] != 'SUCCESS') {
            return Util::returnArrEr('code error!');
        }
        $param = [
            'app_id' => $content['appid'],
            'out_trade_no' => $content['out_trade_no'],//订单号
            'total_fee' => $content['total_fee'] / 100,
            'openid' => $content['openid'],//用户标识
            'payType' => 1,
            'trade_no' => $content['transaction_id'],//流水号
        ];
        return static::payOrder($param);

    }

    /**
     * Des:支付宝支付
     * Name: aliOrderPay
     * @return array
     * @author 倪宗锋
     */
    public static function aliOrderPay()
    {
        /***支付结果判定***/
        if ($_POST['trade_status'] != 'TRADE_SUCCESS') {
            return Util::returnArrEr('code error!');
        }
        $params = [
            'app_id' => $_POST['app_id'],
            'out_trade_no' => $_POST['out_trade_no'],//订单号
            'total_fee' => intval($_POST['buyer_pay_amount']),
            'openid' => $_POST['buyer_id'],//用户标识
            'payType' => 2,
            'trade_no' => $_POST['trade_no'],//流水号
        ];
        return static::payOrder($params);
    }

    /**
     * Des:余额支付
     * Name: amountPay
     * @return array
     * @author 倪宗锋
     */
    public static function amountOrderPay()
    {
        $time = $_POST['time'];
        $code = $_POST['code'];
        $code = Util::authCode($code);//将字符串进行解析
        parse_str($code, $data);//将get参数转换成数组
        if (empty($data['time']) || $time != $data['time']) {
            return Util::returnArrEr('code error');
        }
        $params = [
            'app_id' => '',
            'out_trade_no' => $data['out_trade_no'],//订单号
            'total_fee' => intval($data['buyer_pay_amount']),
            'openid' => '',//用户标识
            'payType' => 3,
            'trade_no' => $data['out_trade_no']
        ];
        return static::payOrder($params);
    }

    /**
     * Des:订单支付成功 数据处理
     * Name: payOrder
     * @param $params
     *  payType int 支付方式 1 微信，2支付宝
     * @return array
     * @author 倪宗锋
     */
    public static function payOrder($params)
    {
        $orderIds = $params['out_trade_no'];//订单ID
        $orderStr = explode('_', $orderIds);
        $orderArr = explode('-', $orderStr['0']);
        /********************数据处理 * 循环设置订单支付信息 *******************************/
        $csOrderList = [];
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            //1.循环设置订单支付信息
            foreach ($orderArr as $key => $orderId) {
                $setOrderPay = static::setOrderPay($orderId, $params);//修改订单状态及插入订单支付记录
                if ($setOrderPay['flag'] == false) {
                    $transaction->rollBack();
                    if ($setOrderPay['code'] == '1000') {//如果已经支付 则 返回成功
                        return Util::returnArrSu();
                    }
                    return $setOrderPay;//是否则返回错误信息
                }
                $csOrderType = $setOrderPay['data']['csOrderType'];//成功则重置订单类型
                if ($csOrderType!=0) {
                    $csOrderInfo = ["orderId"=>$orderId,"orderType"=>$csOrderType];
                    $csOrderList[] = $csOrderInfo;
                }
            }
            //2.数据提交
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();//回滚
            return Util::returnArrEr('system error!');
        }
        //3.添加支付成功记录日志
        Util::addOrderLog(0, 0, implode('-', $orderArr), '付款时间', 3);
        //4.发送微信通知
        foreach ($orderArr as $orderIdVal) {
            Util::sendWxMsg(['type' => 1, 'order_id' => $orderIdVal]);
        }
        if (count($csOrderList) == 0) {//自有的产品 则到此结束
            return Util::returnArrSu();
        }
        //5.cs下单
        /******************如果是其他来源产品的订单 * 去cs下订单**/
        $makeOrder = static::makeCsOrder($csOrderList, $params['payType'], $params['trade_no']);
        if ($makeOrder['flag'] == false) {
            foreach ($orderArr as $key => $orderId) {
                $cancel = static::applyCancelOrder($orderId, 0);//微信申请取消订单
                if ($cancel['flag'] == false) {
                    static::sendMsgForCsAddOrderFail($orderId);//发送异常通知
                }
            }
            return Util::returnArrEr('cs error!');
        }
        //6.发送短信通知

        return Util::returnArrSu();
    }

    /**
     * Des:发送酒店确认订单通知
     * Name: sendHotelConfirmMsg
     * @param $order_id
     * @return array
     * @author 倪宗锋
     */
    public static function sendHotelConfirmMsg($order_id)
    {
        try {
            $orderMain = new  OrderMain();
            $orderInfo = $orderMain->getOrderInfoById($order_id);
            if (in_array($orderInfo['category_id'], [3]) == false) {
                return Util::returnArrSu();
            }
            $hotelOrderInfo = $orderMain->getHotelOrderInfo($orderInfo['order_id']);
            $night = count(json_decode($hotelOrderInfo['total_details'], true));
            $siteConfig = Util::getSiteConfig();
            $msg = "预订成功：订单号{$hotelOrderInfo['order_id']}，{$hotelOrderInfo['users']}{$hotelOrderInfo['start_date']}入住";
            $msg .= "{$hotelOrderInfo['hotel_name']}酒店{$hotelOrderInfo['room_name']}{$hotelOrderInfo['prod_cnt']}间{$night}晚，已支付{$hotelOrderInfo['total_money']}元。房间已预留，入住请出示入住人有效身份证件，酒店地址：{$hotelOrderInfo['address']}。订单不能取消修改。特别提示：请直接报{$hotelOrderInfo['users']}办理入住。";
            $msg .= "客服电话：{$siteConfig['kefu_tel']}，遇到任何问题可关注微信公众号“{$siteConfig['web_name']}”，咨询在线客服，服务时间：09:00-21:00，祝您旅途愉快！";
            return Util::sendMessage($msg, $hotelOrderInfo['contacts_phone']);
        } catch (Exception $e) {
            return Util::returnArrEr('发送短信通知失败');
        }
    }

    /**
     * Des:发送未支付通知
     * Name: sendUnPayMsg
     * @param $order_id
     * @param $phone
     * @return array
     * @author 倪宗锋
     */
    public static function sendUnPayMsg($order_id, $phone)
    {
        try {
            $msg = "您有未支付的订单{$order_id}即将超时，请您抓紧时间完成支付。下单后15分钟内未完成支付的订单将被自动取消。";
            return Util::sendMessage($msg, $phone);
        } catch (Exception $e) {
            return Util::returnArrEr('发送短信通知失败');
        }
    }


    /**
     * Des:设置订单支付状态
     * Name: setOrderPay
     * @param $orderId
     * @param $params
     * @return array
     * @author 倪宗锋
     */
    public static function setOrderPay($orderId, $params)
    {
        /**获取订单信息**/
        $orderMain = new OrderMain();
        $orderInfo = $orderMain->getOrderInfoById($orderId);
        /**已支付订单处理*/
        if (!in_array($orderInfo['order_status'], [1, 5])) {//判断订单是否已支付
            if ($params['out_trade_no'] == $orderInfo['pay_order_id']) {//重复请求
                return Util::returnArrEr('order have paid ' . $orderId, '', '', '1000');
            } else {
                static::refundOrderForRepeatPay($params);//订单重复支付退款

                return Util::returnArrEr('order is paid by other  ' . $orderId);
            }
        }
        /**修改订单主表信息*/
        $upArray = [
            'order_id' => $orderId,
            'order_status' => 2,
        ];
        $upFlag = $orderMain->upOrder($upArray, [$orderId]);
        if (!$upFlag) {
            return Util::returnArrEr('order_main update error!');
        }
        /**在支付表添加记录**/
        $payMain = new PayMain();
        $payArray = [
            'pay_type' => $params['payType'],
            'amount_money' => $params['total_fee'],//支付总金额
            'order_money' => $orderInfo['total_money'],
            'pay_user' => 0,
            'order_id' => $orderId,
            'pay_order_id' => $params['out_trade_no'],
            'app_id' => $params['app_id'],
            'open_id' => $params['openid']
        ];
        $payMain->attributes = $payArray;
        $insertFlag = $payMain->insert();
        if (!$insertFlag) {
            return Util::returnArrEr('add pay_main fail!');
        }
        /**在佣金表添加记录**/
        if (Util::checkPattern('intVal', $orderInfo['fx_uid'])) {
            $orderInfoTable = new OrderInfo();
            if ($orderInfo['category_id'] == 4 && empty($orderInfo['sign']) == false) {//巴士自由行产品价格另行计算
                $getCommission = static::getFreeWalkCommission($orderInfo);
            } elseif ($orderInfo['category_id'] == 3) {
                $getCommission = static::getHotelCommission($orderInfo);
            } else {
                $getCommission = $orderInfoTable->getOrderCommission($orderId);
                if (in_array($orderInfo['fx_uid'], [686, 749]) && in_array($orderInfo['prod_cate_id'], [1354, 1346])) {
                    $getCommission = 5 * intval($orderInfo['prod_cnt']);  //人民广场-迪士尼
                }
                if (in_array($orderInfo['fx_uid'], [222]) && in_array($orderInfo['prod_cate_id'], [1354, 2213])) {
                    $getCommission = 17 * intval($orderInfo['prod_cnt']);  //人民广场-迪士尼
                }
                if (in_array($orderInfo['fx_uid'], [80]) && in_array($orderInfo['prod_cate_id'], [1346])) {
                    $getCommission = 5 * intval($orderInfo['prod_cnt']);  //人民广场-迪士尼
                }
                if (in_array($orderInfo['fx_uid'], [80]) && in_array($orderInfo['prod_cate_id'], [1354])) {
                    $getCommission = 15 * intval($orderInfo['prod_cnt']);  //人民广场-迪士尼
                }
                if (in_array($orderInfo['fx_uid'], [80]) && in_array($orderInfo['prod_cate_id'], [2213])) {
                    $getCommission = 15 * intval($orderInfo['prod_cnt']);  //人民广场-迪士尼
                }
                if (in_array($orderInfo['fx_uid'], [686, 823]) && in_array($orderInfo['prod_cate_id'], [2218, 2214])) {
                    $getCommission = 5 * intval($orderInfo['prod_cnt']);  //上海火车站－迪士尼   迪士尼－上海火车站
                }
                if (in_array($orderInfo['fx_uid'], [686, 823]) && in_array($orderInfo['prod_cate_id'], [2213, 1354])) {
                    $getCommission = 5 * intval($orderInfo['prod_cnt']);  //人民广场－迪士尼     迪士尼－人广
                }
                //瑞景木每子   15000189822 分销线路编号：1354   人民广场-迪士尼   20元     2213  迪士尼-人民广场   20元
                if (in_array($orderInfo['fx_uid'], [807]) && in_array($orderInfo['prod_cate_id'], [1354, 2213])) {
                    $getCommission = 10 * intval($orderInfo['prod_cnt']);
                }
            }
            $fxCommission = new FxCommissionInfo();
            $commissionFlag = $fxCommission->add($orderInfo['fx_uid'], $getCommission, $orderId);
            if (!$commissionFlag) {
                return Util::returnArrEr('add orderInfo fail!');
            }
        }
        /**判断订单需求去cs下单的订单类型*/
        $csOrderType = 0;
        if ($orderInfo['prod_source'] == 2) {//产品来源2位cs系统
            $csOrderType = $orderInfo['category_id'];//分类ID
        }
        /**发送订单支付成功通知，通知客服*/
        if ($csOrderType == 0 || in_array($csOrderType, [2, 4, 5])) {//发送下单成功通知
            static::sendMsgForOrderPay($orderInfo);
        }
        $return = [
            'csOrderType' => $csOrderType
        ];
        return Util::returnArrSu('', $return);
    }

    /**
     * Des:获取巴士自由行的佣金
     * Name: getFreeWalkCommission
     * @param $orderInfo
     * @return int
     * @author 倪宗锋
     */
    public function getFreeWalkCommission($orderInfo)
    {
        $orderInfoTable = new OrderInfo();
        $data = [];
        $data['sign'] = $orderInfo['sign'];
        $data['prod_arr'] = json_encode($orderInfoTable->geProdArr($orderInfo['order_id']));//获取票种产品数据
        $data['date'] = $orderInfo['start_date'];
        $data['action'] = 'get_tourist_pay_total';
        $data['org_id'] = '164';
        $getTotalCost = Util::sendCs($data, '/api/wx', 2);
        if ($getTotalCost['flag'] == true) {
            $total_cost = $getTotalCost['data']['list']['extra_info']['total_cost'];//低价
            $cs_total_money = $getTotalCost['data']['list']['total_money'];//零售价
            $insurance_money = $orderInfo['original_price'] - $cs_total_money;//保险金额 = 订单原价-零售价
            //佣金等于 订单金额-零售价-保险金额
            $getCommission = intval($orderInfo['total_money']) - intval($total_cost) - $insurance_money;
        } else {
            $getCommission = 0;
        }
        return $getCommission;
    }

    /**
     * Des:获取酒店的佣金金额
     * Name: getHotelCommission
     * @param $orderInfo
     * @return float|int
     * @author 倪宗锋
     */
    public static function getHotelCommission($orderInfo)
    {
        $orderMain = new OrderMain();
        $params = $orderMain->getHotelOrderInfo($orderInfo['order_id']);
        $roomPrices = json_decode($params['total_details'], true);
        foreach ($roomPrices as &$val) {
            $val['RunDate'] = $val['date'];
            $val['Price'] = $params['prod_cnt'] * $val['price'];
            unset($val['date']);
            unset($val['price']);
        }
        $data = [
            'HotelID' => $params['hotel_id'],
            'RoomID' => $params['room_id'],
            'RoomNum' => $params['prod_cnt'],
            'CheckIn' => $params['start_date'],
            'CheckOut' => $params['end_date'],
            'RoomPrices' => $roomPrices,
            'IfCheckPrice' => 0,
        ];
        $result = Util::sendCs($data, '/hotel/api/get-low-price', 2);
        $getCommission = 0;
        if ($result['flag'] == true) {
            $total_cost = $result['data']['data']['low_price'];//底价
            //佣金等于 订单金额-底价
            if ($total_cost < $orderInfo['total_money']) {
                $getCommission = round($orderInfo['total_money'] - $total_cost, 2);
            }
        }
        return $getCommission;
    }

    /**
     * Des:前往cs下单
     * Name: makeCsOrder
     * @param $csOrderList
     * @param  $payType
     * @param $trade_no
     * @return array
     * @author 倪宗锋
     */
    public static function makeCsOrder($csOrderList,  $payType, $trade_no = '')
    {
        //支付类型 替换成cs
        if ($payType == 3) {
            $pay_type = 275;
        } else if ($payType == 1) {
            $pay_type = 278;
        } else {
            $pay_type = 638;
        }
        foreach ($csOrderList as $key=>$val){
            $csOrderType = $val['orderType'];
            $makeOrder = Util::returnArrSu();
            if ($csOrderType == 1) {//车票
                $makeOrder = static::makeBusTicket([$val['orderId']], $pay_type);
            } elseif ($csOrderType == 2) {//门票
                $makeOrder = static::makeMenPTicket([$val['orderId']], $pay_type);
            } elseif ($csOrderType == 3) {//酒店
                $makeOrder = static::makeHotel([$val['orderId']], $pay_type, $trade_no);
            } elseif ($csOrderType == 4) {//巴士自由行
                $makeOrder = static::makeFreeWalk([$val['orderId']], $pay_type);
            }
            if ($makeOrder['flag'] == false) {
                return $makeOrder;
            }
        }
        return Util::returnArrSu();
    }

    /**
     * Des:酒店下单
     * Name: makeHotel
     * @param $orderArr
     * @param $pay_type
     * @param $trade_no
     * @return array
     * @author 倪宗锋
     */
    public static function makeHotel($orderArr, $pay_type, $trade_no)
    {
        $orderMain = new OrderMain();
        $orderId = $orderArr[0];
        $orderInfo = $orderMain->getHotelOrderInfo($orderId);
        if (empty($orderInfo['order_id'])) {
            return Util::returnArrEr('订单数据异常！');
        }
//        $system = $orderInfo['system'];
        $system = 2;//展示写死
        $siteConfig = Util::getSiteConfig();
        $siteConfig['adm_user_id'] = $siteConfig['adm_user_arr'][$system]['adm_user_id'];//重置配置
        $siteConfig['adm_source_id'] = $siteConfig['adm_user_arr'][$system]['adm_source_id'];//重置配置

        //出行人信息
        $orderContacts = new OrderContacts();
        $passArr = $orderContacts->getPassAngerPeople($orderId);
        $passengerInfo = [];
        if (count($passArr) != 0) {
            foreach ($passArr as $key => $v) {
                $passengerInfo[]['Name'] = $v['contacts_name'];
            }
        }
        //每日价格信息
        $roomPrices = json_decode($orderInfo['total_details'], true);
        $sum_price = 0;
        foreach ($roomPrices as &$val) {
            $val['RunDate'] = $val['date'];
            $val['Price'] = round($val['price'] * ($orderInfo['total_money'] / $orderInfo['original_price']), 2);
            $sum_price = $sum_price + $val['Price'];
            unset($val['date']);
            unset($val['price']);
        }
        $roomPrices[0]['Price'] = round(($orderInfo['total_money'] / $orderInfo['prod_cnt'] - $sum_price + $roomPrices[0]['Price']), 2);
        $send_data = [
            'CreateUserID' => $siteConfig['adm_user_id'],
            'OrderID' => 'fx' . $orderId, //渠道订单号
            'HotelID' => $orderInfo['hotel_id'], //酒店ID
            'RoomID' => $orderInfo['room_id'],  //房型ID
            'DistribID' => $siteConfig['adm_source_id'],//渠道ID
            'RoomNum' => $orderInfo['prod_cnt'], //房间数量
            'CheckIn' => $orderInfo['start_date'],  //入住日期
            'CheckOut' => $orderInfo['end_date'],    //离店日期,
            'TotalPrice' => $orderInfo['total_money'],//订单总价
            'Commission' => $orderInfo['commission'],//佣金
            'Currency' => 'RMB', //币种
            'ContactName' => $orderInfo['contacts_name'],//联系人姓名
            'ContactTel' => $orderInfo['contacts_phone'],  //联系人电话
            'PayType' => $pay_type,   // 638:支付宝支付; 221:现金支付 ;275:授信支付;278:微信支付
            'PayTradeNo' => $trade_no, //支付流水号
            'OrderGuests' => $passengerInfo, //入住人信息
            'Comment' => $orderInfo['remarks'],  //客人备注
            'NeedInvoice' => 0,
            'InvoiceInfos' => [  //发票信息
            ],
            'RoomPrices' => $roomPrices,
        ];
        $curlInterface = new CurlInterface($send_data, 4);
        $curlInterface->setBaseUrl('');
        $ticket_arr_cs = $curlInterface->execute($siteConfig['adm_host1'] . '/hotel/api/book-hotel-order', 'POST');
        if (isset($ticket_arr_cs['code']) && $ticket_arr_cs['code'] == 0) {
            $orderMain->addSpiderOrder($ticket_arr_cs['data']['order_id'], $orderId);
            return Util::returnArrSu();
        } else {
            return Util::returnArrEr();
        }

    }

    /**
     * Des:去cs下车票订单
     * Name: makeBusTicket
     * @param $orderArr
     * @param $pay_type
     * @return array
     * @author 倪宗锋
     */
    public static function makeBusTicket($orderArr, $pay_type)
    {
        $prodCategory = new ProdCategory();
        $orderMain = new OrderMain();
        $orderId = $orderArr[0];
        $cs_prod_str = $orderMain->GetCsBusProdInfo($orderId);
        $system = $cs_prod_str['system'];
        $prod_str = '{1,' . $cs_prod_str['run_id'] . ',' . $cs_prod_str['ticket_id'] . ',' . $cs_prod_str['price'] . ',' . $cs_prod_str['prod_cnt'] . '}';
        $outside_no = 'fx' . $orderId;
        if (count($orderArr) == 2) {
            $orderId = $orderArr[1];
            $cs_prod_str = $orderMain->GetCsBusProdInfo($orderId);
            $prod_str .= '{2,' . $cs_prod_str['run_id'] . ',' . $cs_prod_str['ticket_id'] . ',' . $cs_prod_str['price'] . ',' . $cs_prod_str['prod_cnt'] . '}';
            $outside_no .= '|fx' . $orderId;
        }
        $memo = "";
        if (!empty($cs_prod_str['recom_prod_cate'])) {
            $recomProd = $prodCategory->getInfoById($cs_prod_str['recom_category'],$cs_prod_str['recom_prod_cate']);
            if($recomProd['category_id']==2 && $recomProd['sub_type']==1) {
                $memo = "来源：门票";
            }else if($recomProd['category_id']==2 && $recomProd['sub_type']==2) {
                $memo = "来源：跟团游";
            }
        }

        //联系人信息
        $customer_info_str = '{' . $cs_prod_str['contacts_name'] . ',' . $cs_prod_str['contacts_phone'] . ',150,,'.$memo.'}';
        $time = time();
        $siteConfig = Util::getSiteConfig();
        $siteConfig['adm_user_id'] = $siteConfig['adm_user_arr'][$system]['adm_user_id'];//重置配置
        $siteConfig['adm_source_id'] = $siteConfig['adm_user_arr'][$system]['adm_source_id'];//重置配置
        //受保人信息
        $orderContacts = new OrderContacts();
        $result = $orderContacts->getInsuredPeople($orderId);
        if (count($result) == 0) {
            $buy_insurance = 0;
            $insurance = '';
        } else {
            $j = 0;
            $arr1 = array();
            foreach ($result as $v) {
                $i = 0;
                $arr1[$j][$i] = $v['contacts_name'];
                $arr1[$j][++$i] = $v['contacts_ID'];
                $j++;
            }
            $buy_insurance = 1;
            $insurance = json_encode($arr1);
        }
        //出行人信息
        $orderContacts = new OrderContacts();
        $passArr = $orderContacts->getPassAngerPeople($orderId);
        if (count($passArr) == 0) {
            $passengerInfo = '';
        } else {
            $arr = array();
            foreach ($passArr as $key => $v) {
                $arr[$key]['passenger_name'] = $v['contacts_name'];
                $arr[$key]['passenger_mobile'] = '';
                $arr[$key]['passenger_cardid'] = $v['contacts_ID'];
            }
            $passengerInfo = json_encode($arr);
        }
        $send_data = [
            'auth_code' => Util::authCodeForCs($time),
            'user_key' => $siteConfig['adm_user_key'],
            'user' => $siteConfig['adm_user'],
            'user_id' => $siteConfig['adm_user_id'],
            'request_time' => $time,
            'action' => 'submit_bus_order',
            'prod_str' => $prod_str,
            'order_info_str' => "{{$siteConfig['adm_user_id']},0,{$siteConfig['adm_source_id']},$outside_no,0,{$pay_type},1,1}",
            'customer_info_str' => $customer_info_str,
            'buy_insurance' => $buy_insurance,
            'insurance' => $insurance,
            'passenger_info' => $passengerInfo
        ];
        $curlInterface = new CurlInterface($send_data, 4);
        $curlInterface->setBaseUrl('');
        $ticket_arr_cs = $curlInterface->execute($siteConfig['adm_host1'] . '/api/submit-order', 'POST');
        if (isset($ticket_arr_cs['code']) && $ticket_arr_cs['code'] == 0) {
            if (count($orderArr) == 2) {
                $order_arr = explode(',', $ticket_arr_cs['data']);
                $addSpiderOrder = $orderMain->addSpiderOrder($order_arr[0], $orderArr[0]);
                $addSpiderOrder1 = $orderMain->addSpiderOrder($order_arr[1], $orderArr[1]);
                if ($addSpiderOrder == 0 || $addSpiderOrder1 == 0) {
                    file_put_contents(APP_PATH . '/log/order/error' . date('Y-m-d') . '.log', $orderArr[0] . '在cs 下单失败     ' . date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);
                }
            } else {
                $addSpiderOrder = $orderMain->addSpiderOrder($ticket_arr_cs['data'], $orderArr[0]);
                if ($addSpiderOrder == 0) {
                    file_put_contents(APP_PATH . '/log/order/error' . date('Y-m-d') . '.log', $orderArr[0] . '在cs 下单失败     ' . date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);
                }
            }
            return Util::returnArrSu();
        } else {
            file_put_contents(APP_PATH . '/log/order/error' . date('Y-m-d') . '.log', $orderArr[0] . '在cs 下单失败     ' . date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);
            return Util::returnArrEr();
        }
    }

    /**
     * Des:去cs下门票订单
     * Name: makeBusTicket
     * @param $orderArr
     * @param $pay_type
     * @return array
     * @author 倪宗锋
     */
    public static function makeMenPTicket($orderArr, $pay_type)
    {
        foreach ($orderArr as $orderId) {
            $orderMain = new OrderMain();
            $cs_prod_str = $orderMain->getCsUnBusProdInfo($orderId);//获取非巴士产品的下单产品信息
            if (empty($cs_prod_str['prod_str'])) {
                return Util::returnArrEr('前往cs下单失败');
            }
            $system = $cs_prod_str['system'];
            $outside_no = 'fx' . $orderId;
            //联系人信息
            $customer_info_str = "{{$cs_prod_str['contacts_name']},{$cs_prod_str['contacts_phone']},150,{$cs_prod_str['contacts_ID']}}";
            $time = time();
            $siteConfig = Util::getSiteConfig();
            $siteConfig['adm_user_id'] = $siteConfig['adm_user_arr'][$system]['adm_user_id'];//重置配置
            $siteConfig['adm_source_id'] = $siteConfig['adm_user_arr'][$system]['adm_source_id'];//重置配置
            $send_data = [
                'auth_code' => Util::authCodeForCs($time),
                'user_key' => $siteConfig['adm_user_key'],
                'user' => $siteConfig['adm_user'],
                'user_id' => $siteConfig['adm_user_id'],
                'request_time' => $time,
                'action' => 'submit_ticket_order',
                'main_prod_id' => $cs_prod_str['main_prod_id'],
                'prod_str' => $cs_prod_str['prod_str'],
                'run_date' => $cs_prod_str['run_date'],
                'order_info_str' => "{{$siteConfig['adm_user_id']},0,{$siteConfig['adm_source_id']},$outside_no ,0,{$pay_type},1,1}",
                'customer_info_str' => $customer_info_str
            ];
            if ($cs_prod_str['sub_type'] == 3) {//如果是包车
                $startDate = $cs_prod_str['run_date'];
                $endDate = $cs_prod_str['end_date'];
                //获取天数
                $dayNum = (int) self::count_days($endDate, $startDate) + 1;
                $bus_extra = [
                    "day_num"=> $dayNum,
                    "start_station"=>$cs_prod_str["start_area"],
                    "end_station"=>$cs_prod_str["end_area"],
                    "start_time"=>$cs_prod_str["start_time"]
                ] ;
                $send_data['bus_extra'] =  json_encode($bus_extra,true);
            }
            $curlInterface = new CurlInterface($send_data, 4);
            $curlInterface->setBaseUrl('');
            $ticket_arr_cs = $curlInterface->execute($siteConfig['adm_host1'] . '/api/submit-order', 'POST');
            if ($ticket_arr_cs['code'] == 0) {
                $orderMain->addSpiderOrder($ticket_arr_cs['data'], $orderId);
            } else {
                return Util::returnArrEr('cs下单失败！');
            }
        }
        return Util::returnArrSu();
    }

    public static function count_days($a,$b){
        $a_dt = getdate($a);
        $b_dt = getdate($b);
        $a_new = mktime(12, 0, 0, $a_dt['mon'], $a_dt['mday'], $a_dt['year']);
        $b_new = mktime(12, 0, 0, $b_dt['mon'], $b_dt['mday'], $b_dt['year']);
        return round(abs($a_new-$b_new)/86400);
    }

    /**
     * Des:巴士自由行订单下单
     * Name: makeFreeWalk
     * @param $orderArr
     * @param $pay_type
     * @return array
     * @author 倪宗锋
     */
    public static function makeFreeWalk($orderArr, $pay_type)
    {

        foreach ($orderArr as $orderId) {
            try {
                $orderMain = new OrderMain();
                $prodCate = new ProdCategory();
                $cs_prod_str = $orderMain->getCsFreeWalkProdForMakeOrder($orderId);//获取巴士自由行产品的下单产品信息
                if (empty($cs_prod_str)) {
                    return Util::returnArrEr('前往cs下单失败');
                }
                $orderInfo = $orderMain->getOrderInfoById($orderId);
                $prodInfo = $prodCate->getProdDetail($orderInfo['prod_cate_id']);
                //出行人信息
                $orderContacts = new OrderContacts();
                $passArr = $orderContacts->getPassAngerPeople($orderId);
                if (count($passArr) == 0) {
                    $passengerInfo = '';
                } else {
                    $arr = array();
                    foreach ($passArr as $key => $v) {
                        $arr[$key]['passenger_name'] = $v['contacts_name'];
                        $arr[$key]['passenger_mobile'] = '';
                        $arr[$key]['passenger_cardid'] = $v['contacts_ID'];
                        # modify nizf 联系人证件使用第一个出行人的证件
                        if (empty($v['contacts_ID']) == false && empty($orderInfo['contacts_ID'])) {
                            $orderInfo['contacts_ID'] = $v['contacts_ID'];
                        }
                    }
                    $passengerInfo = json_encode($arr);
                }
                //受保人信息
                $orderContacts = new OrderContacts();
                $result = $orderContacts->getInsuredPeople($orderId);
                if (count($result) == 0) {
                    $buy_insurance = 0;
                    $insurance = '';
                } else {
                    $j = 0;
                    $arr1 = array();
                    foreach ($result as $v) {
                        $i = 0;
                        $arr1[$j][$i] = $v['contacts_name'];
                        $arr1[$j][++$i] = $v['contacts_ID'];
                        $j++;
                    }
                    $buy_insurance = 1;
                    $insurance = json_encode($arr1);
                }
                //联系人信息
                $customer_info = [
                    'customer_name' => $orderInfo['contacts_name'],
                    'customer_mobile' => $orderInfo['contacts_phone'],
                    'customer_id_type' => '150',
                    'customer_id_no' => $orderInfo['contacts_ID'],
                    'customer_memo' => '无'
                ];
                $siteConfig = Util::getSiteConfig();
                $system = $orderInfo['system'];
                $siteConfig['adm_user_id'] = $siteConfig['adm_user_arr'][$system]['adm_user_id'];//重置配置
                $siteConfig['adm_source_id'] = $siteConfig['adm_user_arr'][$system]['adm_source_id'];//重置配置
                //订单信息
                $orderInfoArr = [
                    'user_id' => $siteConfig['adm_user_id'],
                    'member_id' => 2,
                    'outside_sale_org_id' => $siteConfig['adm_source_id'],
                    'outside_sale_order_no' => 'zzcx' . $orderId,
                    'total_money' => $orderInfo['total_money'],
                    'order_book_status' => 0,
                    'pay_type' => $pay_type,
                    'order_pay_status' => 1,
                    'sales_man' => ''
                ];
                //发送报文
                $time = time();
                $data = [
                    'auth_code' => Util::authCodeForCs($time),
                    'user_key' => $siteConfig['adm_user_key'],
                    'user' => $siteConfig['adm_user'],
                    'user_id' => $siteConfig['adm_user_id'],
                    'request_time' => $time,
                    'sign' => $prodInfo['sign'],
                    'date' => $orderInfo['start_date'],
                    'prod_arr' => json_encode($cs_prod_str),
                    'customer_info' => json_encode($customer_info),
                    'order_info' => json_encode($orderInfoArr),
                    'passenger_info' => $passengerInfo,
                    'buy_insurance' => $buy_insurance,
                    'insurance' => $insurance,
                    'action' => 'submit_tourist_order'
                ];
                $ticket_arr_cs = Util::sendCs($data, '/api/wx/', 2, $system);
                if ($ticket_arr_cs['flag']) {
                    $orderMain->addSpiderOrder($ticket_arr_cs['data']['order_title_id'], $orderId);
                    //巴士自由行订单发送短信通知
                    $smg = "您有新的巴士自由行订单了！{$orderInfo['order_name']},微信：{$orderId},CS：{$ticket_arr_cs['data']['order_title_id']}";
                    $siteConfig = Util::getSiteConfig();
                    if (empty($siteConfig['freeWalkOrder']) == false) {
                        Util::sendMessage($smg, $siteConfig['freeWalkOrder']);
                    }
                } else {
                    return Util::returnArrEr('cs下单失败！');
                }
            } catch (Exception $e) {
                return Util::returnArrEr('cs下单失败！');
            }

        }
        return Util::returnArrSu();
    }

    /**
     * Des:下单成功 发送短信通知和RTX通知
     * Name: sendMsgForOrderPay
     * @param $orderInfo
     * @author 倪宗锋
     */
    public static function sendMsgForOrderPay($orderInfo)
    {
        $siteConfig = Util::getSiteConfig();
        //发送提示信息
        if (empty($siteConfig['YunYinPhone']) == false ) {//如果保存了运营电话就发送短信通知
            $msg = "您有新订单了：订单号：{$orderInfo['order_id']} 
订单类型：{$orderInfo['category_name']}
预定产品：{$orderInfo['order_name']} 
数量：{$orderInfo['prod_cnt']}
开始日期：{$orderInfo['start_date']}
结束日期：{$orderInfo['end_date']}
订单金额：￥{$orderInfo['total_money']}
联系人：{$orderInfo['contacts_name']} 
手机:{$orderInfo['contacts_phone']}
请注意查看";
            Util::sendMessage($msg, $siteConfig['YunYinPhone']);
        }
        if (empty($siteConfig['YunYinRTX']) == false) {//如果保存运营rtx则发送订单通知
            $title = '【移动分销】您有新订单了';
            $msg = "订单号：{$orderInfo['order_id']} 
订单类型：{$orderInfo['category_name']}
预定产品：{$orderInfo['order_name']} 
数量：{$orderInfo['prod_cnt']}
开始日期：{$orderInfo['start_date']}
结束日期：{$orderInfo['end_date']}
订单金额：￥{$orderInfo['total_money']}
联系人：{$orderInfo['contacts_name']} 
手机:{$orderInfo['contacts_phone']}
请注意查看";
            Util::sendMsgRTX($siteConfig['YunYinRTX'], $title, $msg);
        }

        if($orderInfo['category_id'] == 2) {//给用户发送短信通知
            $msg = "您预定的“{$orderInfo["order_name"]}{$orderInfo["order_id"]}”已成功；为了保障您的出行，请务必至少提前两小时预定；否则订单款项将原路退回；车牌号及司机信息最晚将于发车前一小时发至您手机上，请注意查看；如遇问题请拨打0571-86693985";
            Util::sendMessage($msg, $orderInfo['contacts_phone']);
        }
    }

    /**
     * Des:下单失败短信通知
     * Name: sendMsgForCsAddOrderFail
     * @param $orderId
     * @author 倪宗锋
     */
    public static function sendMsgForCsAddOrderFail($orderId)
    {
        if (empty($siteConfig['YunYinRTX']) == false) {//如果保存运营rtx则发送订单通知
            $title = '【移动分销】下单异常';
            $msg = "订单号：$orderId
同步巴士订单失败，且自动退款失败，
请立即通知开发人员。
请注意查看";
            Util::sendMsgRTX($siteConfig['YunYinRTX'], $title, $msg);
        }
    }

    /**
     * Des:下单
     * Name: makeOrder
     * @param $param_arr
     * @return array
     * @author 倪宗锋
     */
    public static function makeOrder($param_arr)
    {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            /**去程下单*/
            $order_go = static::createOrder($param_arr['go_params']);//去程下单
            if ($order_go['flag'] == false) {
                $transaction->rollBack();//数据提交
                return $order_go;
            }
            $orderId = $order_go['data']['order_id'];//订单ID
            $param_arr['total_money'] = (int)$order_go['data']['total_money'];//
            if ($param_arr['if_back'] == 1) {
                /**返程下单*/
                $order_back = static::createOrder($param_arr['back_params']);//返程下单
                if ($order_back['flag'] == false) {
                    $transaction->rollBack();//数据提交
                    return $order_back;
                }
                $orderId .= '-' . $order_back['data']['order_id'];
                $param_arr['total_money'] += $order_back['data']['total_money'];
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();//回滚
            return Util::returnArrEr('下单失败[1008]');
        }
        //设置下单成功返回值
        $return = static::setMakeOrderReturn($orderId, $param_arr['total_money'], $param_arr['go_params']['system'], $param_arr['go_params']['contacts_phone'], $param_arr['go_params']['fx_uid'],$param_arr['parent_order']);
        return Util::returnArrSu('', $return);
    }

    /**
     * Des:设置订单返回值
     * Name: setMakeOrderReturn
     * @param $orderId
     * @param $total_money
     * @param $contacts_phone
     * @param $system
     * @param $fx_uid
     * @return array
     * @author 倪宗锋
     */
    public static function setMakeOrderReturn($orderId, $total_money, $contacts_phone, $system, $fx_uid,$parent_order)
    {
        //生成日志-开始 错误不终止程序
        //发送 微信通知 错误不终止程序
        try {
            if ($system == 2) {
                $checkLogin = LoginService::checkLogin();//如果当前用户是登录状态 则用户ID为当前用户 否则根据用户手机号去绑定
                if ($checkLogin['flag'] == true) {
                    $u_uid = LoginService::$uid;
                } else {
                    $shUser = new ShUser();
                    $u_uid = $shUser->getUidByPhone(trim($contacts_phone));
                }
                $u_type = 3;//微信用户下单
            } else {
                $u_uid = $fx_uid;
                $u_type = 2;//分销用户下单
            }
            Util::addOrderLog($u_uid, $u_type, $orderId, '创建时间', 1);
        } catch (Exception $e) {
        }
        //设置返回值
        $siteConfig = Util::getSiteConfig();
        if($parent_order != "") {
            $orderId = $orderId.'-'.$parent_order;
        }
        $return = [
            'order_id' => $orderId,
            'pay_url' => $siteConfig['host_name'] . $siteConfig['payUrl'] . $orderId,
            'total_money' => $total_money
        ];
        return $return;
    }


    /**
     * Function Description:本地数据库添加订单数据
     * Function Name: createOrder
     * @param $param_arr
     *
     * @return array
     *
     * @author 娄梦宁
     */
    public static function createOrder($param_arr)
    {
        $order_info = new OrderInfo();
        $order_main = new OrderMain();
        $order_contacts = new OrderContacts();
        $prod_cate = new ProdCategory();
        //获取产品数量
        $prod_cnt = 0;
        foreach ($param_arr['prod_arr'] as $val) {
            $prod_cnt += $val['prod_count'];
        }
        $param_arr['prod_cnt'] = $prod_cnt;
        /*****获取订单信息***/
        $category = $prod_cate->getProdCateInfo($param_arr['pro_cate_id']);
        if (empty($category)) {
            return Util::returnArrEr('下单失败[1001]');
        }
        $param_arr['category_id'] = $category['category_id'];
        $param_arr['sub_type'] = $category['sub_type'];
        if (empty($param_arr['prod_arr'])) {
            return Util::returnArrEr('下单失败[1002]');
        }
        $totalMoney = static::getTotalMoney($param_arr, $category);//获取价格、如有需要计算子产品价格的则返回从cs获取到的产品的产品价格
        if ($totalMoney['flag'] == false) {
            return Util::returnArrEr('下单失败[1003]');
        }
        if (isset($totalMoney['data']['prod_arr'])) {
            $param_arr['prod_arr'] = $totalMoney['data']['prod_arr'];
        }
        //新增保险价格--2017-10-26 娄梦宁
        $param_arr['total_money'] = $totalMoney['data']['total_money'];
        if ($param_arr['category_id'] == 1 && (!empty($param_arr['is_buy_insurance']) && $param_arr['insurance_list'])) {
            $param_arr['insurance_price'] = 3;
            $param_arr['total_money'] = $param_arr['total_money'] + count($param_arr['insurance_list']) * $param_arr['insurance_price'];
        }
        //新增自由行保险价格--2017-12-08 田玲菲
        if ($param_arr['category_id'] == 4 && (!empty($param_arr['is_buy_insurance']) && $param_arr['insurance_list'])) {
            $param_arr['total_money'] = $param_arr['total_money'] + count($param_arr['insurance_list']) * $param_arr['insurance_price'];
        }

        /**********1.插入order_main***************/
        $fxUser = new FxUser();
        $fxUserInfo = $fxUser::findOne($param_arr['fx_uid']);
        $param_arr['main_user_id'] = $fxUserInfo['main_user_id'];//获取运营联系人
        $param_arr['end_date'] = date('Y-m-d', strtotime($param_arr['start_date']) + 3600 * 24 * (intval($param_arr['days']) - 1));
        $param_arr['order_name'] = $category['pro_cate_name'];
        $param_arr['prod_source'] = 1;//产品来源 1、系统自增，2、cs
        if (empty($param_arr['start_area'])) {
            $param_arr['start_area'] = $category['start_area'];
        }
        if (empty($param_arr['end_area'])) {
            $param_arr['end_area'] = $category['end_area'];
        }
        if ($category['category_id'] == 1 || empty($category['sign']) == false) {
            $param_arr['prod_source'] = 2;
        }
        $shUser = new ShUser();
        $param_arr['sh_uid'] = $shUser->getUidByPhone(trim($param_arr['contacts_phone']));//订单归属于 手机号对应的用户
        $insertOrderMain = $order_main->insertOrder($param_arr);
        if (!$insertOrderMain) {
            return Util::returnArrEr('下单失败[1004]');
        }
        $orderId = $order_main->order_id;
        /**********2.插入order_info***************/
        $freeWalkerProdArr = [];
        if ($category['category_id'] == 4) {//如果是巴士自由行
            $freeWalker = new  FreeWalker();
            $getProd = $freeWalker->getProdArr($category, $param_arr['start_date']);
            $freeWalkerProdArr = $getProd['data'];
        }
        foreach ($param_arr['prod_arr'] as $val) {
            if ($val['prod_count'] == 0) {
                continue;
            }
            if (empty($val['prod_price'])) {//没有 价格 则为0
                $val['prod_price'] = 0;
            }
            foreach ($freeWalkerProdArr as $freeWalkProd) {//重置价格
                if ($freeWalkProd['prod_id'] == $val['prod_id']) {
                    $val['prod_price'] = $freeWalkProd['prod_price'];
                }
            }
            $insertOrderInfo = $order_info->insertInfo($val, $orderId, $category);
            if (!$insertOrderInfo) {
                return Util::returnArrEr('下单失败[1005]');
            }
        }
        /**********4.插入联系人信息***************/
        $insertOrderContacts = $order_contacts->insertContacts($param_arr, $orderId);
        if (!$insertOrderContacts) {
            return Util::returnArrEr('下单失败[1006]');
        }
        /**********5.产品销售数量+***************/
        $addProdCnt = $prod_cate->addCount($param_arr['pro_cate_id'], $prod_cnt);
        if ($addProdCnt === false) {
            return Util::returnArrEr('下单失败[1007]');
        }
        /**************6.添加受保人信息***********************/
        $addInsured = static::addInsured($param_arr, $orderId, $param_arr['insurance_price']);
        if ($addInsured['flag'] == false) {
            return $addInsured;
        }
        /**************7.添加乘车人信息***********************/
        $addPassAnger = static::addPassAnger($param_arr, $orderId);
        if ($addPassAnger['flag'] == false) {
            return $addPassAnger;
        }
        return Util::returnArrSu('', ['order_id' => $orderId, 'total_money' => $param_arr['total_money']]);
    }

    /**
     * Des:添加保险单出行人信息
     * Name: addInsured
     * @param $param_arr
     * @param $orderId
     * @return array
     * @author 倪宗锋
     */
    public static function addInsured($param_arr, $orderId, $insurance_price = 0)
    {
        if (!empty($param_arr['is_buy_insurance']) && $param_arr['insurance_list']) {
            foreach ($param_arr['insurance_list'] as $v) {
                $arr = array(
                    'contacts_name' => $v['passenger_name'],
                    'contacts_ID' => $v['passenger_cardid'],
                    'insurance_price' => $insurance_price
                );
                $orderContacts = new OrderContacts();
                $res = $orderContacts->addInsuredPeople($arr, $orderId);
                if (!$res) {
                    return Util::returnArrEr('下单失败[1008]');
                }
            }
        }
        return Util::returnArrSu();
    }

    /**
     * Des:添加保险单出行人信息
     * Name: addInsured
     * @param $param_arr
     * @param $orderId
     * @return array
     * @author 倪宗锋
     */
    public static function addPassAnger($param_arr, $orderId)
    {
        if (empty($param_arr['passanger_arr']) == false) {
            foreach ($param_arr['passanger_arr'] as $v) {
                $arr = array(
                    'contacts_name' => $v['passenger_name'],
                    'contacts_ID' => $v['passenger_cardid']
                );
                $orderContacts = new OrderContacts();
                $res = $orderContacts->addPassAngerPeople($arr, $orderId);
                if (!$res) {
                    return Util::returnArrEr('下单失败[1009]');
                }
            }
        }
        return Util::returnArrSu();
    }

    /**
     * Des:添加酒店拓展信息
     * Name: addHotelExtra
     * @param $param_arr
     * @param $orderId
     * @return array
     * @author 倪宗锋
     */
    public static function addHotelExtra($param_arr, $orderId)
    {
        if (empty($param_arr['hotel_extra']) == false) {
            $data = $param_arr['hotel_extra'];
            $data['main_order_id'] = $orderId;
            $hotelExtra = new OrderHotelExtra();
            $addFlag = $hotelExtra->addRow($data);
            return $addFlag;
        }
        return Util::returnArrSu();
    }

    /**
     * Des:获取订单总价格
     * Name: getTotalMoney
     * @param $params
     * @param $category
     * @return array
     * @author 倪宗锋
     */
    public static function getTotalMoney($params, $category)
    {
        /********如果是cs门票订单* 去CS获取订单价格***********/
        if ($category['category_id'] == 2 && empty($category['sign']) == false ) {
            $ticket = new MenP();//门票通用函数
            $getTotalMoney = $ticket->getOrderPriceFromCs($category, $params['start_date'], $params['prod_arr'], $params['days']);
            if ($getTotalMoney['flag'] == false) {
                return $getTotalMoney;
            }
            $totalMoney = $getTotalMoney['data'];
        }
        elseif ($category['category_id'] == 4 && empty($category['sign']) == false) {
            $ticket = new FreeWalker();//巴士自由行
            $getTotalMoney = $ticket->getPrice($params);
            if ($getTotalMoney['flag'] == false) {
                return $getTotalMoney;
            }
            $totalMoney = $getTotalMoney['data'];
        } /****默认直接读取数据库中产品的数据********/
        else {
            $prod_main = new ProdMain();
            $totalMoney = $prod_main->getTotalMoney($params['prod_arr']);//获取订单总金额
            $totalMoney = ['total_money' => $totalMoney];
        }
        //微信系统的巴士产品打92折
        if ($params['system'] == 2 && $params['category_id'] == 1) {
            $totalMoney['total_money'] = static::getBusDiscountPrice($params['pro_cate_id'], $totalMoney['total_money'], $params['prod_cnt']);
        }
        return Util::returnArrSu('', $totalMoney);
    }

    /**
     * Des:获取巴士票的打折后的价格
     * Name: getBusDiscountPrice
     * @param $pro_cate_id
     * @param $total_money
     * @param $prod_cnt int 产品数量
     * @return float
     * @author 倪宗锋
     */
    public static function getBusDiscountPrice($pro_cate_id, $total_money, $prod_cnt = 1)
    {
        $siteConfig = Util::getSiteConfig();
        foreach ($siteConfig['bus_discount_list'] as $discountVal) {
            if (in_array($pro_cate_id, $discountVal['id'])) {//如果是独立设置的就直接返回
                $total_money = ceil($total_money * $discountVal['discount']);
                return $total_money;
            }
        }
        $total_money = ceil($total_money * $siteConfig['all_discount']);
        $total_money = $total_money - $siteConfig['all_discount_price'] * $prod_cnt;//全局减金额
        if ($total_money <= 0) {
            $total_money = 1;
        }
        return $total_money;
    }

    /**
     * Des:无产品下单
     * Name: makeUnProdOrder
     * @param $data
     * @return array
     * @author 倪宗锋
     */
    public static function makeUnProdOrder($data)
    {
        $param_arr = [
            'total_money' => $data['total_money'],//总基恩
            'pro_cate_id' => 0,//产品ID
            'prod_cnt' => $data['prod_cnt'],//产品数量
            'order_name' => $data['order_name'],//订单名称
            'fx_uid' => $data['fx_uid'],//分销商ID
            'start_date' => $data['start_date'],//开始日期
            'start_time' => $data['start_time'],//开始时间
            'sh_uid' => $data['sh_uid'],//用户ID
            'end_date' => $data['end_date'],//接收日期
            'end_time' => empty($data['end_time']) ? '00:00:00' : $data['end_time'],//结束时间
            'category_id' => $data['category_id'],//订单类型
            'system' => $data['system'],//系统
            'contacts_name' => $data['contacts_name'],//联系人
            'contacts_ID' => $data['contacts_ID'],//联系人证件ID
            'contacts_phone' => $data['contacts_phone'],//联系人手机号
            'prod_source' => empty($data['prod_source']) ? 1 : $data['prod_source'],//产品来源
            'start_area' => $data['start_area'],//起始地点
            'end_area' => $data['end_area'],//结束地点
            'passanger_arr' => empty($data['passanger_arr']) ? [] : $data['passanger_arr'],
            'hotel_extra' => empty($data['hotel_extra']) ? [] : $data['hotel_extra'],
            'remark'=>empty($data['remark'])?"":$data['remark']
        ];
        $order_contacts = new OrderContacts();
        $order_main = new OrderMain();
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            /**********1.插入order_main***************/
            if (empty($param_arr['sh_uid'])) {
                $shUser = new ShUser();
                $param_arr['sh_uid'] = $shUser->getUidByPhone($param_arr['contacts_phone']);
            }
            $insertOrderMain = $order_main->insertOrder($param_arr);
            if (!$insertOrderMain) {
                $transaction->rollBack();//回滚
                return Util::returnArrEr('下单失败[1004]');
            }
            $orderId = $order_main->order_id;

            /**********4.插入联系人信息***************/
            $insertOrderContacts = $order_contacts->insertContacts($param_arr, $orderId);
            if (!$insertOrderContacts) {
                $transaction->rollBack();//回滚
                return Util::returnArrEr('下单失败[1006]');
            }
            /**************7.添加乘车人信息***********************/
            $addPassAnger = static::addPassAnger($param_arr, $orderId);
            if ($addPassAnger['flag'] == false) {
                return $addPassAnger;
            }
            /**************9.添加酒店拓展信息***********************/
            $addPassAnger = static::addHotelExtra($param_arr, $orderId);
            if ($addPassAnger['flag'] == false) {
                return $addPassAnger;
            }
            $transaction->commit();//数据提交
        } catch (Exception $e) {
            $transaction->rollBack();//回滚
            return Util::returnArrEr('下单失败[1008]');
        }
        return Util::returnArrSu('', ['order_id' => $orderId, 'total_money' => $param_arr['total_money']]);
    }

    /**
     * Des:对重复支付的订单进行退款
     * Name: refundOrderForSetPay
     * @param $params
     *  pay_type 支付类型 1、微信 2、支付宝 3、余额支付
     * @return array
     * @author 倪宗锋
     */
    public static function refundOrderForRepeatPay($params)
    {
        if ($params['payType'] == 3) {
            return Util::returnArrSu();
        }
        $data = [
            'order_id' => $params['out_trade_no'],
            'total_fee' => $params['total_fee'],
            'refund_fee' => $params['total_fee'],
            'app_id' => $params['app_id']
        ];
        $payType = $params['payType'];
        $return = PayService::cancel($data, $payType);
        return $return;
    }


    /**
     * Des:发送微信退款通知
     * Name: sendRefundTemplateMsg
     * @param $order_id int
     * @param $total_money int 退款金额
     * @author 倪宗锋
     * @return array
     */
    public static function sendRefundWxMsg($order_id, $total_money)
    {

        $payMain = new PayMain();
        $getInfo = $payMain->getPayInfo($order_id);///获取支付信息
        if ($getInfo['pay_type'] != 1) {
            return Util::returnArrEr('非微信支付订单！');
        }
        $open_id = $getInfo['open_id'];//微信用户OPENID
        $siteConfig = Util::getSiteConfig();
        $url = $siteConfig['host_name'] . $siteConfig['order_detail'] . $order_id;
        /**
         * {{first.DATA}}
         * 订单号：{{keyword1.DATA}}
         * 退款原因：{{keyword2.DATA}}
         * 退款金额：{{keyword3.DATA}}
         * {{remark.DATA}}
         */
        $data = [
            'first' => ['value' => '您好，您的退款申请已成功退款，请确认查收。', 'color' => '#743A3A'],
            'keyword1' => ['value' => $order_id, 'color' => '#4191ff'],
            'keyword2' => ['value' => '订单取消', 'color' => '#4191ff'],
            'keyword3' => ['value' => $total_money . '元', 'color' => '#4191ff'],
            'remark' => ['value' => '温馨提示：如有疑问，请咨询在线客服', 'color' => '#743A3A']
        ];
        $flag = WeChatService::sendWxTemplate($open_id, 'sendRefundWxMsg', $url, $data);
        if ($flag == true) {
            return Util::returnArrSu();
        }
        return Util::returnArrEr('发送失败！');
    }

    /**
     * Des:预定成功微信通知
     * Name: sendCreateOrderWxMsg
     * @param $order_id
     * @return array
     * @author 倪宗锋
     */
    public static function sendCreateOrderWxMsg($order_id)
    {
        if (Util::checkPattern('intVal', $order_id) == false) {
            return Util::returnArrEr('params error');
        }
        $orderMain = new OrderMain();
        $getInfo = $orderMain->getSendCreateWxMsg($order_id);
        if (empty($getInfo['open_id'])) {
            return Util::returnArrEr('非微信支付订单！');
        }
        $open_id = $getInfo['open_id'];//微信用户OPENID
        $siteConfig = Util::getSiteConfig();
        $url = $siteConfig['host_name'] . $siteConfig['order_detail'] . $order_id;

        ///汽车票下单通知
        if ($getInfo['category_id'] == 1) {
            $data = [
                'first' => ['value' => '您的订单已预订成功，马上为您出票。', 'color' => '#743A3A'],
                'keyword1' => ['value' => $order_id, 'color' => '#4191ff'],
                'keyword2' => ['value' => $getInfo['users'], 'color' => '#4191ff'],
                'keyword3' => ['value' => $getInfo['start_area'] . ' - ' . $getInfo['end_area'], 'color' => '#4191ff'],
                'keyword4' => ['value' => $getInfo['start_date'] . ' ' . $getInfo['start_time'], 'color' => '#4191ff'],
                'remark' => ['value' => '温馨提示：请提前15分钟到站乘车，上车时请出示订单号进行检票上车，如需帮助，请咨询微信在线客服', 'color' => '#743A3A']
            ];
            $flag = WeChatService::sendWxTemplate($open_id, 'sendCreateOrderWxMsg_1', $url, $data);
        } ///门票下单通知
        else if ($getInfo['category_id'] == 2) {
            $data = [
                'first' => ['value' => '您好，您的门票订单已预订成功。', 'color' => '#743A3A'],
                'OrderID' => ['value' => $order_id, 'color' => '#4191ff'],
                'PkgName' => ['value' => $getInfo['order_name'] . ' ' . $getInfo['prod_cnt'], 'color' => '#4191ff'],
                'TakeOffDate' => ['value' => $getInfo['start_date'] . ' ' . $getInfo['start_time'], 'color' => '#4191ff'],
                'remark' => ['value' => '使用方法：凭预订成功后收到的短信提示换票或刷身份证入园，未使用前短信请勿删除、不能转发。如不慎删除，请联系在线客服。', 'color' => '#743A3A']
            ];
            $flag = WeChatService::sendWxTemplate($open_id, 'sendCreateOrderWxMsg_2', $url, $data);
        } else if ($getInfo['category_id'] == 3) {
            $hotelOrder = $orderMain->getHotelOrderInfo($order_id);
            $data = [
                'first' => ['value' => "您好，您已经成功预订{$hotelOrder['hotel_name']}。等待酒店确认接单。如酒店不接单将全额退款至您的付款账户。", 'color' => '#743A3A'],
                'keyword1' => ['value' => $order_id, 'color' => '#4191ff'],//订单号
                'keyword2' => ['value' => $hotelOrder['start_date'], 'color' => '#4191ff'],//入住日期
                'keyword3' => ['value' => $hotelOrder['all_days'] . '晚', 'color' => '#4191ff'],//入住天数
                'keyword4' => ['value' => $hotelOrder['room_name'], 'color' => '#4191ff'],//房型名称
                'keyword5' => ['value' => $hotelOrder['prod_cnt'] . '间', 'color' => '#4191ff'],//房间数
                'remark' => ['value' => '如有疑问，请致电' . $siteConfig['kefu_tel'] . "或关注微信公众号“{$siteConfig['web_name']}”，咨询在线客服，服务时间：09:00 - 21:00。", 'color' => '#743A3A']
            ];
            $flag = WeChatService::sendWxTemplate($open_id, 'sendCreateOrderWxMsg_3', $url, $data);
        } else {
            return Util::returnArrEr('暂时只支持汽、门票和酒店下单通知！');
        }
        if ($flag == true) {
            return Util::returnArrSu();
        }
        return Util::returnArrEr('发送失败！');
    }

    /**
     * Des:发送佣金变更微信通知信息 发送给分销
     * Name: sendCommissionWxMsg
     * @param  $order_id
     * @return array
     * @author 倪宗锋
     */
    public static function sendCommissionWxMsg($order_id)
    {
        if (Util::checkPattern('intVal', $order_id) == false) {
            return Util::returnArrEr('params error');
        }
        $fxCommission = new FxCommissionInfo();
        $getInfo = $fxCommission->getSendWxMsg($order_id);
        if (empty($getInfo['open_id'])) {
            return Util::returnArrEr('非微信支付订单！');
        }
        if (empty($getInfo['commission'])) {
            return Util::returnArrEr('没有佣金不发送通知');
        }
        $open_id = $getInfo['open_id'];//微信open_id
        $siteConfig = Util::getSiteConfig();
        $url = $siteConfig['fx_host'] . '/web/fx/order_detail.html?order_id=' . $order_id;//分销订单详情页面
        $data = [
            'first' => ['value' => '恭喜你有新的分销佣金入账。', 'color' => '#743A3A'],
            'keyword1' => ['value' => $order_id, 'color' => '#4191ff'],
            'keyword2' => ['value' => $getInfo['category_name'], 'color' => '#4191ff'],
            'keyword3' => ['value' => '已完成', 'color' => '#4191ff'],
            'keyword4' => ['value' => $getInfo['total_money'] . '元', 'color' => '#4191ff'],
            'keyword5' => ['value' => $getInfo['commission'] . '元', 'color' => '#4191ff'],
            'remark' => ['value' => '分销佣金入账，你离月薪十万还差一小步，再接再厉哦！', 'color' => '#743A3A']
        ];
        $flag = WeChatService::sendWxTemplate($open_id, 'sendCommissionWxMsg', $url, $data, '#7B68EE', $siteConfig['fx_wechat']);
        if ($flag == true) {
            return Util::returnArrSu();
        }
        return Util::returnArrEr('发送失败！');
    }

    /**
     * Des:发送巴士出行短信通知
     * Name: sendRunBusWxMsg
     * @param $data
     * @return array
     * @author 倪宗锋
     */
    public static function sendRunBusWxMsg($data)
    {
        $open_id = $data['open_id'];//微信open_id
        $siteConfig = Util::getSiteConfig();
        $url = $siteConfig['host_name'] . $siteConfig['order_detail'] . $data['order_id'];//微信订单详情页
        $data = [
            'first' => ['value' => '出行车辆通知', 'color' => '#743A3A'],
            'keyword1' => ['value' => $data['bus_no'], 'color' => '#4191ff'],
            'keyword2' => ['value' => $data['seat_name'], 'color' => '#4191ff'],
            'keyword3' => ['value' => $data['area'], 'color' => '#4191ff'],
            'keyword4' => ['value' => $data['run_date'], 'color' => '#4191ff'],
            'keyword5' => ['value' => '联系在线客服获取', 'color' => '#4191ff'],
            'remark' => ['value' => '温馨提示：司机将会在发车前5-10分钟与您联系，请保持手机畅通', 'color' => '#743A3A']
        ];
        $flag = WeChatService::sendWxTemplate($open_id, 'sendRunBusWxMsg', $url, $data);
        if ($flag == true) {
            return Util::returnArrSu();
        }
        return Util::returnArrEr('发送失败！');
    }

    /**
     * Des:发送取消订单分销通知
     * Name: sendCancelOrderWxMsg
     * @param $order_id
     * @return array
     * @author 倪宗锋
     */
    public static function sendCancelOrderWxMsg($order_id)
    {
        if (Util::checkPattern('intVal', $order_id) == false) {
            return Util::returnArrEr('params error');
        }
        $orderMain = new OrderMain();
        $getInfo = $orderMain->getSendCreateWxMsg($order_id);
        if (empty($getInfo['open_id'])) {
            return Util::returnArrEr('非微信支付订单！');
        }
        $open_id = $getInfo['open_id'];//微信用户OPENID
        $siteConfig = Util::getSiteConfig();
        $url = $siteConfig['host_name'] . $siteConfig['order_detail'] . $order_id;
        if ($getInfo['category_id'] == 3) {
            $hotelOrder = $orderMain->getHotelOrderInfo($order_id);
            $star_date = date('m月d日', strtotime($hotelOrder['start_date']));
            $data = [
                'first' => ['value' => "您预定的{$star_date}入住的{$hotelOrder['room_name']}房型({$hotelOrder['prod_cnt']}间{$hotelOrder['all_days']}晚) 的订单已被酒店确认无房，请您选择其他的房型入住。您所支付的金额将会全额退回您的支付账号。请注意查收。", 'color' => '#743A3A'],
                'keyword1' => ['value' => $hotelOrder['hotel_name'], 'color' => '#4191ff'],//酒店名称
                'keyword2' => ['value' => $hotelOrder['start_date'], 'color' => '#4191ff'],//入住日期
                'keyword3' => ['value' => $hotelOrder['end_date'], 'color' => '#4191ff'],//离店日期
                'remark' => ['value' => '如有疑问，请致电' . $siteConfig['kefu_tel'] . "或关注微信公众号“{$siteConfig['web_name']}”，咨询在线客服，服务时间：09:00 - 21:00。", 'color' => '#743A3A']
            ];
            $flag = WeChatService::sendWxTemplate($open_id, 'sendCancelOrderWxMsg_3', $url, $data);
        } else {
            return Util::returnArrEr('暂时只支持酒店取消通知！');
        }
        if ($flag == true) {
            return Util::returnArrSu();
        }
        return Util::returnArrEr('发送失败！');
    }

    /**
     * Des:分销下单通知
     * Name: sendFxCreateOrder
     * @param $order_id
     * @return array
     * @author 倪宗锋
     */
    public
    static function sendFxCreateOrder($order_id)
    {
        if (Util::checkPattern('intVal', $order_id) == false) {
            return Util::returnArrEr('params error');
        }
        $fxCommission = new FxCommissionInfo();
        $getInfo = $fxCommission->getSendWxMsg($order_id);
        if (empty($getInfo['open_id'])) {
            return Util::returnArrEr('非微信支付订单！');
        }
        if (empty($getInfo['open_id'])) {
            return Util::returnArrEr('没有分销商不发送通知');
        }
        $open_id = $getInfo['open_id'];//微信open_id
        $siteConfig = Util::getSiteConfig();
        $url = $siteConfig['fx_host'] . '/web/fx/order_detail.html?order_id=' . $order_id;//分销订单详情页面
        $data = [
            'first' => ['value' => '进单啦！有人通过扫描您的蜘蛛二维码下单成功', 'color' => '#743A3A'],
            'keyword1' => ['value' => $getInfo['order_name'], 'color' => '#4191ff'],//产品名称
            'keyword2' => ['value' => $order_id, 'color' => '#4191ff'],//订单号
            'keyword3' => ['value' => $getInfo['prod_cnt'], 'color' => '#4191ff'],//人数
            'keyword4' => ['value' => $getInfo['total_money'], 'color' => '#4191ff'],//金额
            'remark' => ['value' => '详情请查看您的分销订单列表。', 'color' => '#743A3A']
        ];
        $flag = WeChatService::sendWxTemplate($open_id, 'sendFxCreateOrder', $url, $data, '#7B68EE', $siteConfig['fx_wechat']);
        if ($flag == true) {
            return Util::returnArrSu();
        }
        return Util::returnArrEr('发送失败！');
    }

    /**
     * Des:发送酒店订单确认通知
     * Name: sendConfirmWxMsg
     * @param $order_id
     * @return array
     * @author 倪宗锋
     */
    public static function sendConfirmWxMsg($order_id)
    {
        if (Util::checkPattern('intVal', $order_id) == false) {
            return Util::returnArrEr('params error');
        }
        $orderMain = new OrderMain();
        $getInfo = $orderMain->getSendCreateWxMsg($order_id);
        if (empty($getInfo['open_id'])) {
            return Util::returnArrEr('非微信支付订单！');
        }
        $open_id = $getInfo['open_id'];//微信用户OPENID
        $siteConfig = Util::getSiteConfig();
        $url = $siteConfig['host_name'] . $siteConfig['order_detail'] . $order_id;
        $hotelOrder = $orderMain->getHotelOrderInfo($order_id);
        $star_date = date('m月d日', strtotime($hotelOrder['start_date']));
        $data = [
            'first' => ['value' => "您预定的{$star_date}入住的{$hotelOrder['room_name']}房型({$hotelOrder['prod_cnt']}间{$hotelOrder['all_days']}晚) 的订单已被酒店确认接单，请您于入住当日到酒店前台办理相关手续", 'color' => '#743A3A'],
            'order' => ['value' => $hotelOrder['order_id'], 'color' => '#4191ff'],//订单号
            'Name' => ['value' => $hotelOrder['users'], 'color' => '#4191ff'],//入住人
            'datein' => ['value' => $hotelOrder['start_date'], 'color' => '#4191ff'],//入住日期
            'dateout' => ['value' => $hotelOrder['end_date'], 'color' => '#4191ff'],//离店日期
            'number' => ['value' => $hotelOrder['prod_cnt'] . '间', 'color' => '#4191ff'],//房间数量
            'room type' => ['value' => $hotelOrder['room_name'], 'color' => '#4191ff'],//房型名称
            'pay' => ['value' => $hotelOrder['total_money'], 'color' => '#4191ff'],//订单总价
            'remark' => ['value' => '如有疑问，请致电' . $siteConfig['kefu_tel'] . "或关注微信公众号“{$siteConfig['web_name']}”，咨询在线客服，服务时间：09:00 - 21:00。", 'color' => '#743A3A']
        ];
        $flag = WeChatService::sendWxTemplate($open_id, 'sendConfirmWxMsg', $url, $data);
        if ($flag == true) {
            return Util::returnArrSu();
        }
        return Util::returnArrEr('发送失败！');
    }

    /**
     * Des:发送酒店出行通知
     * Name: sendTravelTipsWxMsg
     * @param $params
     * @return array
     * @author 倪宗锋
     */
    public static function sendTravelTipsWxMsg($params)
    {
        $open_id = $params['open_id'];//微信用户OPENID
        $siteConfig = Util::getSiteConfig();
        $url = $siteConfig['host_name'] . $siteConfig['order_detail'] . $params['order_id'];
        $data = [
            'first' => ['value' => "您好，{$params['hotel_name']}万分期待您的入住，为了让您有更好的入住体验，请您尽量于当天14点-18点到店，错开前台办理入住的高峰时段。", 'color' => '#743A3A'],
            'OrderID' => ['value' => $params['order_id'], 'color' => '#4191ff'],//订单号
            'HotelName' => ['value' => $params['hotel_name'], 'color' => '#4191ff'],//入住人
            'CheckInDate' => ['value' => $params['start_date'], 'color' => '#4191ff'],//入住日期
            'CheckOutDate' => ['value' => $params['end_date'], 'color' => '#4191ff'],//离店日期
            'remark' => ['value' => '如有疑问，请致电' . $siteConfig['kefu_tel'] . "或关注微信公众号“{$siteConfig['web_name']}”，咨询在线客服，服务时间：09:00 - 21:00。", 'color' => '#743A3A']
        ];
        $flag = WeChatService::sendWxTemplate($open_id, 'sendTravelTipsWxMsg', $url, $data);
        if ($flag == true) {
            return Util::returnArrSu();
        }
        return Util::returnArrEr('发送失败！');

    }

    /**
     * Des:校验是否可定
     * Name: checkHotel
     * @param $params
     * @return array
     * @author 倪宗锋
     */
    public
    static function checkHotel($params)
    {
        $roomPrices = json_decode($params['total_details'], true);
        foreach ($roomPrices as &$val) {
            $val['RunDate'] = $val['date'];
            $val['Price'] = $val['price'];
            unset($val['date']);
            unset($val['price']);
        }

        $data = [
            'HotelID' => $params['hotel_id'],
            'RoomID' => $params['room_id'],
            'RoomNum' => $params['prod_cnt'],
            'CheckIn' => $params['start_date'],
            'CheckOut' => $params['end_date'],
            'RoomPrices' => $roomPrices,
            'IfCheckPrice' => 0,
        ];
        $result = Util::sendCs($data, '/hotel/api/check-room-avail', 2);
        if ($result['flag'] == true) {
            return Util::returnArrSu('', $result['data']['data']);
        }
        return Util::returnArrEr($result['msg']);
    }

}